/*
 * @Author: lixu lixu@puchigames.com
 * @Date: 2025-01-03 16:49:48
 * @LastEditors: lixu lixu@puchigames.com
 * @LastEditTime: 2025-09-16 17:59:04
 * @FilePath: /go-helper/ixRedis/sorted_set.go
 * @Description: Redis 有序集合操作
 */
package ixRedis

import "github.com/garyburd/redigo/redis"

// ZAdd 添加有序集合成员
func (c *Client) ZAdd(key string, score float64, member interface{}) error {
	conn, err := c.getConn()
	if err != nil {
		return err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	_, err = conn.Do("ZADD", fullKey, score, member)
	return err
}

// ZRange 获取有序集合范围
func (c *Client) ZRange(key string, start, stop int64) ([]string, error) {
	conn, err := c.getConn()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	return redis.Strings(conn.Do("ZRANGE", fullKey, start, stop))
}

// ZRangeWithScores 获取有序集合范围（带分数）
func (c *Client) ZRangeWithScores(key string, start, stop int64) ([]string, error) {
	conn, err := c.getConn()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	return redis.Strings(conn.Do("ZRANGE", fullKey, start, stop, "WITHSCORES"))
}

// ZRem 删除有序集合成员
func (c *Client) ZRem(key string, members ...interface{}) (int64, error) {
	if len(members) == 0 {
		return 0, nil
	}

	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	args := make([]interface{}, len(members)+1)
	args[0] = fullKey
	for i, member := range members {
		args[i+1] = member
	}

	return redis.Int64(conn.Do("ZREM", args...))
}

// ZCard 获取有序集合成员数量
func (c *Client) ZCard(key string) (int64, error) {
	conn, err := c.getConn()
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	// 构建带前缀的键
	fullKey := c.buildKey(key)
	return redis.Int64(conn.Do("ZCARD", fullKey))
}
